package org.example.domain.strategy.service.rule.chain.factory;

import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainMap;

    @Resource
    private IStrategyRepository strategyRepository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainMap) {
        this.logicChainMap = logicChainMap;
    }

    public ILogicChain openLogicChain(Long strategyId) {
        List<String> ruleModels = strategyRepository.queryRuleModelsByStrategyId(strategyId);
        if (null == ruleModels || ruleModels.isEmpty()) {
            return logicChainMap.get("default");
        }

        ILogicChain now = logicChainMap.get(ruleModels.get(0));
        for (int i = 1; i < ruleModels.size(); i++) {
            ILogicChain chain = logicChainMap.get(ruleModels.get(i));
            now.appendNext(chain);
            now = chain;
        }
        now.appendNext(logicChainMap.get("default"));
        return logicChainMap.get(ruleModels.get(0));
    }
}
